import express from 'express';
import req from '../../lib/axios'
const $API = 'https://www.gwdang.com/trend/data_www'
import tbApi from '../../lib/tbapi'; // 淘宝接口API
import moment from "moment";
const router = express.Router();

router.post('/', async function (Request, Response, next) {
  let param = Request.body
  // if (!param.itemLink) {
  //   await getItemLink(param.goodsId).then(res => {
  //     param.itemLink = res
  //   });
  // }
  req.get($API, {
    v: 2,
    dp_id: param.goodsId,
    show_prom: true,
    get_coupon: 0
  }).then(res => {
    if(res.series){
      // 获取多少天的记录
      let dayJson = {
        0: 0,
        180: 1,
        60: 2,
        30: 3,
      }
      let history = res.series[dayJson[param.day]]
      // 设置最高最低
      history.min = history.min / 100
      history.max = history.max / 100
      //拆分x，y轴为两个数组
      let listX = [], listY = []
      history.data.forEach((item, index) => {
        listX.unshift(moment(item.x * 1000).format('YYYY.MM.DD'))
        listY.unshift(item.y / 100)
      })
      // X、Y轴数据填充
      history.categories = listX
      history.series = [{
        name: '价格',
        color: '#294d7d',
        data: listY
      }]
      // 辅助标线
      history.extra = {
        markLine: {
          data: [{
            value: history.min,
          }]
        }
      }
      Response.json({
        ...history
      })
    }else{
      // 接口返回出错信息
      console.log(res.msg)
      Response.status(300).send({ message: res.message });
    }
  });
});

function getItemLink(goodsId, Response) {
  // 通过商品ID获取商品链接
  return new Promise((resolve, reject) => {
    tbApi.index({
      method: 'taobao.tbk.item.info.get', // 淘宝客商品详情查询
      num_iids: goodsId,
    }).then(res => {
      console.log(res.tbk_item_info_get_response.results.n_tbk_item[0].item_url)
      if (res.error_response) {
        // 接口返回出错信息
        Response.status(300).send({ message: res.error_response.sub_msg });
      } else {
        resolve(res.tbk_item_info_get_response.results.n_tbk_item[0].item_url)
      }
    })
  })
}


module.exports = router;